package com.test.fileapplication.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.github.stepup18.CustomEllipsizeTextView;
import com.test.fileapplication.R;
import com.test.fileapplication.util.RemoteFile;
import com.test.fileapplication.util.RemoteFileListSortByTime;
import com.test.fileapplication.base.BaseMultiItemAdapter;
import com.test.fileapplication.util.DensityUtil;
import com.test.fileapplication.util.FileIconUtils;
import com.test.fileapplication.util.ScreenUtils;
import com.test.fileapplication.util.TimeUtils;

import org.greenrobot.greendao.annotation.NotNull;

import java.util.ArrayList;
import java.util.List;

public class FileFragmentSortByTimeAdapter<T extends MultiItemEntity> extends BaseMultiItemAdapter<T> {

    private Context mContext;
    private int canEditFileTotal;//可编辑的文件总数

    public FileFragmentSortByTimeAdapter(Context context) {
        super(R.layout.item_file_sort_by_time_parent, R.layout.item_file_grid, R.layout.item_file_list);
        this.mContext = context;
    }

    public void setDatas(@NotNull List<T> data) {
        getData().clear();
        notifyDataSetChanged();
        canEditFileTotal = 0;
        for (int i = 0; i < data.size(); i++) {
            T t = data.get(i);
            if (t instanceof RemoteFileListSortByTime) {
                RemoteFileListSortByTime item = (RemoteFileListSortByTime) t;
                for (RemoteFile file : item.getList()) {
                    if (file.isCanSelected(mContext) && file.canSelectedBackUpOrRevert()
                            && file.canOperation() && file.canUpload()) {
                        canEditFileTotal++;
                    }
                }
            } else {
                if (((RemoteFileListSortByTime.ByTimeFile) t).getFile().isCanSelected(mContext)
                        && ((RemoteFileListSortByTime.ByTimeFile) t).getFile().canSelectedBackUpOrRevert()
                        && ((RemoteFileListSortByTime.ByTimeFile) t).getFile().canOperation()
                        && ((RemoteFileListSortByTime.ByTimeFile) t).getFile().canUpload()) {
                    canEditFileTotal++;
                }
            }
        }
        getData().addAll(data);
        notifyDataSetChanged();
        //setNewData(data);
    }

    @Override
    protected void convert(BaseViewHolder helper, T item) {
        switch (item.getItemType()) {
            case 0:
                setTitle(helper, (RemoteFileListSortByTime) item);
                break;
            case 1:
            case 2:
                setItem(helper, ((RemoteFileListSortByTime.ByTimeFile) item).getFile());
                break;
        }
    }

    //    public interface OnDeleteListener {
    //        void onDelete(RemoteFile pos);
    //    }
    //
    //    OnDeleteListener listener;
    //
    //    public void setOnDeleteListener(OnDeleteListener listener) {
    //        this.listener = listener;
    //    }

    private void setItem(final BaseViewHolder helper, final RemoteFile item) {
        ImageView itemIcon = helper.getView(R.id.itemIcon);
        int width;

        ImageView itemBU = helper.getView(R.id.iv_file_backup_icon);
        if (item.getBackupStatus() == 3) {
            itemBU.setVisibility(View.VISIBLE);
        } else {
            itemBU.setVisibility(View.GONE);
        }

        switch (column) {
            case 1:
                //                TextView delete = helper.getView(R.id.tv_delete);
                //                delete.setTag(item);
                //                delete.setOnClickListener(new View.OnClickListener() {
                //                    @Override
                //                    public void onClick(View view) {
                //                        listener.onDelete((RemoteFile) view.getTag());
                //                    }
                //                });
                ImageView ivNormalMode = helper.getView(R.id.ivNormalMode);
                if (!item.isCanSelected(mContext) || !item.canSelectedBackUpOrRevert() || !item.canOperation() || !item.canUpload()) {
                    helper.setGone(R.id.cbSelectMode, false);
                    if (isSelectMode()) {
                        ivNormalMode.setVisibility(View.INVISIBLE);
                    } else {
                        ivNormalMode.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (isSelectMode()) {
                        helper.setGone(R.id.cbSelectMode, true);
                        ivNormalMode.setVisibility(View.INVISIBLE);
                        if (isChecked(item)) {
                            helper.setImageResource(R.id.cbSelectMode, R.drawable.icon_checked);
                        } else {
                            helper.setImageResource(R.id.cbSelectMode, R.drawable.icon_no_checked);
                        }
                    } else {
                        helper.setGone(R.id.cbSelectMode, false);
                        //文件夹显示右箭头，文件不显示右箭头
                        if (item.getCategory().equals("1")) {
                            ivNormalMode.setVisibility(View.INVISIBLE);
                        } else {
                            ivNormalMode.setVisibility(View.VISIBLE);
                        }
                    }
                }

                helper.setGone(R.id.tv_time, item.isCanSelected(mContext));

                //                helper.setText(R.id.itemName, item.getFileName());

                TextView tv_name = helper.getView(R.id.itemName);
                setTvName(tv_name, item);

                helper.setText(R.id.tv_time, TimeUtils.longToString(item.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
                width = (int) ((ScreenUtils.getScreenWidth(mContext) / 1080f) * DensityUtil.dip2px(46, mContext));
                //                LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams) itemIcon
                //                .getLayoutParams();
                if ("2".equals(item.getCategory())) {
                    //如果是文件夹
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                    params.height = (width * 59 / 74);
                    params.width = width;
                    itemIcon.setLayoutParams(params);
                    FileIconUtils.getThumnailURL(mContext, item, itemIcon, false); //获取缩略图
                    RelativeLayout.LayoutParams paramsBU = (RelativeLayout.LayoutParams) itemBU.getLayoutParams();
                    paramsBU.bottomMargin = (int) DensityUtil.dip2px(4.5f, mContext);
                    paramsBU.rightMargin = (int) DensityUtil.dip2px(0, mContext);
                    itemBU.setLayoutParams(paramsBU);

                } else {
                    RelativeLayout.LayoutParams paramsBU = (RelativeLayout.LayoutParams) itemBU.getLayoutParams();
                    paramsBU.rightMargin = (int) DensityUtil.dip2px(4, mContext);
                    paramsBU.bottomMargin = (int) DensityUtil.dip2px(0f, mContext);
                    itemBU.setLayoutParams(paramsBU);

                    if (!TextUtils.isEmpty(item.getThumbnail())) { //有缩略图
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                        params.width = DensityUtil.dip2px(52, mContext);
                        params.height = params.width;
                        itemIcon.setLayoutParams(params);
                        FileIconUtils.getThumnailURL(mContext, item, itemIcon, false); //获取缩略图
                    } else {  //没有缩略图
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                        params.width = DensityUtil.dip2px(52, mContext);
                        params.height = DensityUtil.dip2px(64, mContext);
                        itemIcon.setLayoutParams(params);
                        FileIconUtils.getThumnailURL(mContext, item, itemIcon, false); //获取缩略图
                    }
                }
                break;
            default:
                TextView tvName = helper.getView(R.id.itemName);
                RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) tvName.getLayoutParams();
                params1.width = DensityUtil.dip2px(74, mContext);
                tvName.setLayoutParams(params1);
//                DataUtils.setTvName(tvName, item);
                setTvName(tvName, item);
                //                helper.setText(R.id.itemName, item.getFileName());
                ImageView itemCB = helper.getView(R.id.cbSelectMode);
                if (!item.isCanSelected(mContext) || !item.canSelectedBackUpOrRevert() || !item.canOperation() || !item.canUpload()) {
                    //                    helper.setGone(R.id.cbSelectMode, false);
                    itemCB.setVisibility(View.GONE);
                } else {
                    if (isSelectMode()) {
                        //                        helper.setGone(R.id.cbSelectMode, true);
                        itemCB.setVisibility(View.VISIBLE);
                        if (isChecked(item)) {
                            helper.setImageResource(R.id.cbSelectMode, R.drawable.icon_checked);
                        } else {
                            helper.setImageResource(R.id.cbSelectMode, R.drawable.icon_no_checked);
                        }
                    } else {
                        //                        helper.setGone(R.id.cbSelectMode, false);
                        itemCB.setVisibility(View.GONE);
                    }
                }
                width = (int) ((ScreenUtils.getScreenWidth(mContext) - DensityUtil.dip2px(2 * 16 + 2 * 53, mContext)) / 3);
                if ("2".equals(item.getCategory())) {
                    //如果是文件夹
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                    params.width = (int) DensityUtil.dip2px(74, mContext);
                    params.height = (int) DensityUtil.dip2px(59, mContext);
                    params.topMargin = (int) DensityUtil.dip2px(31, mContext);
                    itemIcon.setLayoutParams(params);
                    FileIconUtils.getThumnailURL(mContext, item, itemIcon, false); //获取缩略图

                    RelativeLayout.LayoutParams paramsCB = (RelativeLayout.LayoutParams) itemCB.getLayoutParams();
                    paramsCB.topMargin = (int) DensityUtil.dip2px(0, mContext);
                    paramsCB.rightMargin = (int) DensityUtil.dip2px(0, mContext);
                    itemCB.setLayoutParams(paramsCB);

                    RelativeLayout.LayoutParams paramsBU = (RelativeLayout.LayoutParams) itemBU.getLayoutParams();
                    paramsBU.bottomMargin = (int) DensityUtil.dip2px(7, mContext);
                    paramsBU.rightMargin = (int) DensityUtil.dip2px(0, mContext);
                    itemBU.setLayoutParams(paramsBU);

                } else {
                    RelativeLayout.LayoutParams paramsCB = (RelativeLayout.LayoutParams) itemCB.getLayoutParams();
                    paramsCB.topMargin = (int) DensityUtil.dip2px(-13, mContext);
                    paramsCB.rightMargin = (int) DensityUtil.dip2px(-4, mContext);
                    itemCB.setLayoutParams(paramsCB);


                    RelativeLayout.LayoutParams paramsBU = (RelativeLayout.LayoutParams) itemBU.getLayoutParams();
                    if (true) {
                        paramsBU.rightMargin = (int) DensityUtil.dip2px(0, mContext);
                    } else {
                        paramsBU.rightMargin = (int) DensityUtil.dip2px(4.5f, mContext);
                    }
                    itemBU.setLayoutParams(paramsBU);

                    if (!TextUtils.isEmpty(item.getThumbnail())) { //有缩略图
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                        if (true) {
                            params.width = (int) DensityUtil.dip2px(74, mContext);
                            params.height = (int) DensityUtil.dip2px(74, mContext);
                            params.topMargin = (int) DensityUtil.dip2px(14, mContext);
                        } else {
                            params.width = (int) DensityUtil.dip2px(52, mContext);
                            params.height = (int) DensityUtil.dip2px(64, mContext);
                            params.topMargin = (int) DensityUtil.dip2px(20, mContext);
                        }

                        itemIcon.setLayoutParams(params);
                        FileIconUtils.getThumnailURL(mContext, item, itemIcon, false); //获取缩略图
                    } else {  //没有缩略图
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) itemIcon.getLayoutParams();
                        if (true) {
                            params.width = (int) DensityUtil.dip2px(74, mContext);
                            params.height = (int) DensityUtil.dip2px(74, mContext);
                            params.topMargin = (int) DensityUtil.dip2px(20, mContext);
                        } else {
                            params.width = (int) DensityUtil.dip2px(52, mContext);
                            params.height = (int) DensityUtil.dip2px(64, mContext);
                            params.topMargin = (int) DensityUtil.dip2px(25, mContext);
                        }

                        itemIcon.setLayoutParams(params);
                        Glide.with(mContext).load("").diskCacheStrategy(DiskCacheStrategy.ALL).into(itemIcon); //获取缩略图
                    }
                }
                break;
        }

//        if (isSelectMode()) {
//            helper.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (!item.isCanSelected(mContext)) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.public_folder_not_click_tip));
//                        return;
//                    }
//
//                    if (!item.canSelectedBackUpOrRevert()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_back_up_revert_not_operation));
//                        return;
//                    }
//
//                    if (!item.canOperation()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_piliang_not_operation));
//                        return;
//                    }
//
//                    if (!item.canUpload()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_upload_not_operation));
//                        return;
//                    }
//
//                    if (isChecked(item)) {
//                        removeCheckList(item);
//                        notifyItemChanged(helper.getAdapterPosition());
//                    } else {
//                        addCheckList(item);
//                        notifyItemChanged(helper.getAdapterPosition());
//                    }
//                }
//            });
//
//            if (checkedList.size() != getCanEditFileTotal()) {
//                onItemClickInterface.selectedAll();
//            } else {
//                onItemClickInterface.notSelectedAll();
//            }
//        } else {
//            helper.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    onItemClickInterface.onItemClick(item);
//                }
//            });

            /**
             * item的长按事件
             */
//            helper.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//                @Override
//                public boolean onLongClick(View v) {
//                    if (!item.isCanSelected(mContext)) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.public_folder_not_click_tip));
//                        return true;
//                    }
//
//                    if (!item.canSelectedBackUpOrRevert()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_back_up_revert_not_operation));
//                        return true;
//                    }
//
//                    if (!item.canOperation()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_piliang_not_operation));
//                        return true;
//                    }
//
//                    if (!item.canUpload()) {
//                        ToastUtil.showCenterHasImageToast(mContext,
//                                mContext.getResources().getString(R.string.file_upload_not_operation));
//                        return true;
//                    }
//
//                    if (onItemClickInterface != null) {
//                        onItemClickInterface.onItemLongCick(item);
//                        addCheckList(item);
//                        notifyItemChanged(helper.getAdapterPosition());
//                        onItemClickInterface.selectCount(checkedList, checkedList.size());
//                    }
//                    return true;
//                }
//            });
//        }

    }

    private void setTitle(final BaseViewHolder helper, final RemoteFileListSortByTime item) {
        FrameLayout flSwitch = helper.getView(R.id.fl_switch);
        ImageView ivSwitch = helper.getView(R.id.iv_switch);
        if (item.getShowDate().equals("9999-99-99")) {
            helper.setGone(R.id.tvDate, false);
            flSwitch.setVisibility(View.GONE);
        } else {
            TextView tvDate = helper.getView(R.id.tvDate);
            tvDate.setText(item.getShowDate());
            tvDate.setVisibility(View.VISIBLE);
            flSwitch.setVisibility(View.VISIBLE);
        }

        if (item.isExpanded()) {
            ivSwitch.setImageResource(R.mipmap.select_video_close);
        } else {
            ivSwitch.setImageResource(R.mipmap.select_video_open);
        }
        flSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.isExpanded()) {
                    collapse(helper.getAdapterPosition());
                } else {
                    expand(helper.getAdapterPosition());
                }
                notifyItemChanged(helper.getAdapterPosition());
            }
        });
    }

    public int getCanEditFileTotal() {
        return canEditFileTotal;
    }

    /**
     * 字符串显示到textView, textView maxLines=2
     * 如果字符串太长显示不下，则用省略号代替
     * 省略号的位置在第一行末尾
     *
     * @param textView 显示字符串的view
     * @param str      要显示的字符串
     * @param width    显示字符串的view的宽
     * @return 处理后带省略号的字符串
     */
    private String ellipsizeString(TextView textView, String str, int width) {
        Paint paint = textView.getPaint();
        //文字总宽小于2倍的view宽，说明小于2行，直接返回
        if (paint.measureText(str) < 2 * width) {
            return str;
        }

        //存储显示到view的每行文字
        List<String> list = new ArrayList<>();

        int len = 0;
        int start, end = 0;

        while (len < str.length()) {
            len += end;
            int count = paint.breakText(str, end, str.length(), true, width, null);
            start = end;
            end = end + count;
            list.add(str.substring(start, end));
        }

        //第一行文字末尾三个字符替换成省略号
        String line1 = list.get(0);
        line1 = line1.substring(0, line1.length() - 3) + "...";

        //最后一行半的文字从末尾向前截取一行文字
        String endLine = list.get(list.size() - 1);
        int endLineWidth = (int) paint.measureText(endLine);
        String minorEndLine = list.get(list.size() - 2);
        int minorCuteCount = paint.breakText(minorEndLine, 0, minorEndLine.length(), true, endLineWidth, null);
        String line2 = minorEndLine.substring(minorCuteCount, minorEndLine.length()) + endLine;

        return line1 + line2;
    }

    public void setTvName(TextView tvName, RemoteFile remoteFile) {
        CustomEllipsizeTextView customName = (CustomEllipsizeTextView) tvName;
        String fileName = remoteFile.getFileName();
        customName.setText(fileName);
        if (fileName.indexOf(".") > -1) {
            int lastIndex = fileName.lastIndexOf(".");
            String suffix = fileName.substring(lastIndex + 1);
            int len = fileName.substring(0, lastIndex).length();
            if (len > 2) {
                String ellWords = fileName.substring(lastIndex - 2, lastIndex);
                int count = getWordCountRegex(ellWords);
                int ellCount = 2;
                if (count > 2) {
                    ellCount = 1;
                }
                int ellIndex = suffix.length() + ellCount + 1;
                customName.setEllipsizeIndex(ellIndex);
            }
        }
    }

    private static int getWordCountRegex(String s) {
        s = s.replaceAll("[^\\x00-\\xff]", "**");
        int length = s.length();
        return length;
    }
}
